package com.aiss.ws.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiss.ws.Entity.AgreenonItem;
import com.aiss.ws.Entity.CurseItem;
import com.aiss.ws.Entity.PayBabyItem;
import com.aiss.ws.Entity.PayWxItem;
import com.aiss.ws.R;
import com.aiss.ws.adapter.SurePayAdatper;
import com.aiss.ws.demo.PayDemoActivity;
import com.aiss.ws.httptools.GetJSONObjectPostUtil;
import com.aiss.ws.httptools.GetJsonListener;
import com.aiss.ws.utils.Command;
import com.aiss.ws.utils.Futil;
import com.aiss.ws.utils.SetViewHeight;
import com.aiss.ws.utils.Url;
import com.aiss.ws.wx.Constants;
import com.lidroid.xutils.exception.HttpException;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

/**
 * Created by chenqiang on 16/5/17.
 * 确认支付
 */
@EActivity(R.layout.activity_surepay)
public class SurePayActivity extends BaseActivity {

    private static Activity act;

    private IWXAPI api;

    private PayBabyItem item = new PayBabyItem();

    private PayWxItem itemWx = new PayWxItem();

    @ViewById(R.id.button)
    TextView button;

    @ViewById(R.id.price)
    TextView price;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what==Command.HANDLECODE21){
                try {
                    JSONObject obj = (JSONObject) msg.obj;
                    item.setOut_trade_no(obj.getString("out_trade_no"));
                    item.setBody(obj.getString("body"));
                    item.setNotify_url(obj.getString("notify_url"));
                    item.setPayment_type(obj.getString("payment_type"));
                    item.setSubject(obj.getString("subject"));
                    item.setTotal_fee(obj.getString("total_fee"));
                    startActivity(new Intent(context,PayDemoActivity.class).putExtra("item",item));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else if(msg.what== Command.HANDLECODE22){


                try {
                    JSONObject object = (JSONObject) msg.obj;
                    JSONObject obj =  object.getJSONObject("return_data");
                    itemWx.setAppid(obj.getString("appid"));
                    itemWx.setNoncestr(obj.getString("noncestr"));
                    itemWx.setPackage_w(obj.getString("package"));
                    itemWx.setPartnerid(obj.getString("partnerid"));
                    itemWx.setPrepayid(obj.getString("prepayid"));
                    itemWx.setSign(obj.getString("sign"));
                    itemWx.setTimestamp(obj.getString("timestamp"));
                    getWx(itemWx);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    private Context context = this;

    @ViewById(R.id.title)
    TextView title_tv;


    @Click(R.id.back)
    void setBack(){
        finish();
    }

    @AfterViews
    void init(){
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        act = this;
        title_tv.setText("确认支付");
        adapter = new SurePayAdatper(agreenonItem.getDatas(),this);
        listView.setAdapter(adapter);
        SetViewHeight.setListViewHeightBasedOnChildren(listView);
        adapter.notifyDataSetChanged();
    }

    @ViewById(R.id.listView)
    ListView listView;

    @Extra
    AgreenonItem agreenonItem;

    @ViewById(R.id.edittext)
    EditText edittext;

    @ViewById(R.id.zhifubao_img1)
    ImageView zhifubao_img1;

    @ViewById(R.id.zhifubao_img2)
    ImageView zhifubao_img2;

    @ViewById(R.id.weixin_img1)
    ImageView weixin_img1;

    @ViewById(R.id.weixin_img2)
    ImageView weixin_img2;

    /**
     * 点击支付宝
     */
    @Click(R.id.zhifubao_rel)
    void setZhifubao_img(){
        zhifubao_img1.setVisibility(View.VISIBLE);
        zhifubao_img2.setVisibility(View.GONE);
        weixin_img1.setVisibility(View.GONE);
        weixin_img2.setVisibility(View.VISIBLE);
    }

    /**
     * 点击微信
     */
    @Click(R.id.weixin_rel)
    void setWeixin_img(){
        zhifubao_img1.setVisibility(View.GONE);
        zhifubao_img2.setVisibility(View.VISIBLE);
        weixin_img1.setVisibility(View.VISIBLE);
        weixin_img2.setVisibility(View.GONE);
    }

    /**
     * 去支付
     */
    @Click(R.id.pay_tv)
    void pay_tv(){

        if(zhifubao_img1.getVisibility()==View.VISIBLE){
            zhifubao();
        }else{
            weixin();
        }

    }

    @Click(R.id.button)
    void button(){
        HashMap<String,String> map = new HashMap<>();
        map.put("type","check_ticket");
        map.put("ticket",edittext.getText().toString());
        Futil.AddHashMap(map);
        new GetJSONObjectPostUtil(Url.ORDER, map, new GetJsonListener() {
            @Override
            public void onSuccessed(JSONObject result) {
                try {
                    if(result.getString("state").equals("1")){
                        String str_price = result.getString("return_data");
                        List<CurseItem> datas = agreenonItem.getDatas();
                        int num = 0;
                        for(int i = 0 ; i < datas.size();i++){
                            num += Integer.parseInt(datas.get(i).getBuy_type_price());
                        }
                        price.setText(num-Integer.parseInt(str_price));
                    }else{
                        showMessage(result.getString("return_data"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                showMessage("请检查网络连接");
            }
        });
    }



    private SurePayAdatper adapter;

    private String product = "";
    void zhifubao(){
        HashMap<String,String> map = new HashMap<>();
        map.put("type","submit");

        for(int i = 0 ; i < agreenonItem.getDatas().size();i++){
            product += agreenonItem.getDatas().get(i).getIdx()+"|"+agreenonItem.getDatas().get(i).getBuy_type_id()+",";
        }

        map.put("product",product);
        map.put("ticket",edittext.getText().toString());
        map.put("pay_type","1");
        Futil.xutils(Url.ORDER,map,handler, Command.HANDLECODE21);
    }

    void weixin(){
        HashMap<String,String> map = new HashMap<>();
        map.put("type","submit");

        for(int i = 0 ; i < agreenonItem.getDatas().size();i++){
            product += agreenonItem.getDatas().get(i).getIdx()+"|"+agreenonItem.getDatas().get(i).getBuy_type_id()+",";
        }
        map.put("product",product);
        map.put("ticket",edittext.getText().toString());
        map.put("pay_type","2");
        Futil.xutils(Url.ORDER,map,handler, Command.HANDLECODE22);

    }

    void getWx(PayWxItem item){
        Toast.makeText(context, "获取订单中...", Toast.LENGTH_SHORT).show();
        try{
//
            PayReq req = new PayReq();
            //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
            req.appId			= item.getAppid();
            req.partnerId		= item.getPartnerid();
            req.prepayId		= item.getPrepayid();
            req.nonceStr		= item.getNoncestr();
            req.timeStamp		= item.getTimestamp();
            req.packageValue	= item.getPackage_w();
            req.sign			= item.getSign();

//                    req.extData			= "app data"; // optional
//                    Toast.makeText(context, "正常调起支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
//            api.registerApp("wxfc96546da97d4463");
            api.sendReq(req);
        }catch(Exception e){
            Log.e("PAY_GET", "异常："+e.getMessage());
            Toast.makeText(context, "异常："+e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public static Activity getActivity(){
        return act;
    }




}
